const router = require("../../../utils/router.js").router;
const Toast = require("../../../utils/notice.js").Toast;
Page({

    data: {
        choosenImg: "",
        itemName: "",
        itemNum: 0,
        img: {
            maxCount: 1,
            sizeType: ['original', 'compressed'],
            sourceType: ['album', 'camera'],
        }
    },

    onShow: function () {

    },

    chooseImg() {
        var that = this;
        const imgInfo = this.data.img;
        wx.chooseImage({
          count: imgInfo.maxCount,
          sizeType: imgInfo.sizeType,
          sourceType: imgInfo.sourceType,
          success: function(res) {
              that.setData({
                  choosenImg: res.tempFilePaths[0],
              })
          }
        })
    },

    itemNameInput(e) {
        const inputValue = e.detail.value;
        this.setData({
            itemName: inputValue,
        })
    },


    itemNumInput(e) {
        const inputValue = e.detail.value;
        this.setData({
            itemNum: inputValue,
        })
    },

    handleUpload() {

        if (!this.checkParams()) {
            return;
        }

        Toast.loading("上传中");
        const itemName = this.data.itemName;
        const itemNum = this.data.itemNum;
        const filePath = this.data.choosenImg;
        const userModal = wx.getStorageSync('user');
        wx.uploadFile({
          filePath: filePath,
          name: 'pictures',
          url: router.host + router.addItem,
          formData: {
              userModal: userModal,
              name: itemName,
              number: itemNum,
          },
          success: function(res) {
              let resData = JSON.parse(res.data);
              if (resData.code == 502) {
                  wx.navigateTo({
                    url: '../../login/login',
                  })
                  return;
              } else if (resData.code == 200) {
                  Toast.success("上传成功！");
              }
          },
        })

    },

    checkParams() {
        const itemName = this.data.itemName;
        const itemNum = this.data.itemNum;
        const filePath = this.data.choosenImg;
        if (itemName == null || itemName == undefined || itemName.trim() == "") {
            Toast.fail("请填写物品名！");
            return false;
        }
        if (filePath == null || filePath == undefined || filePath.trim() == "") {
            Toast.fail("请上传图片！");
            return false;
        }
        if (itemNum == null || itemNum == undefined || itemNum.trim() == "") {
            Toast.fail("请填写仓储数量！");
            return false;
        }
        return true;
    }
})